﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BlockMain_Api.Models;
using BlockMain_Class;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace BlockMain_Api.Controllers
{
    public class AddBlockController : Controller
    {
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            try
            {
                Cache.Get("num");
            }
            catch (Exception e)
            {
                return Content("请开启Redis服务" + e.Message);
            }
            return View();
        }


        /// <summary>
        /// 入链接口 
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(int peerid, string data)
        {
            if (CheckConnect())
            {
                var list = GetPeerList.Get();
                Record r = new Record();
                r.PeerId = peerid;
                r.NowPeer = "0";
                r.JsonData = data;
                r.State = 0;
                r.AddTime = DateTime.Now;
                Addredis(r);
                return Json(new Messages { state = 200, msg = "ok" });
            }
            else {
                return Json(new Messages { state = 500, msg = "存在节点未开启服务" });
            }
     
        }

        /// <summary>
        ///验证节点是否宕机 
        /// </summary>
        /// <returns></returns>
        public bool CheckConnect()
        {
            return true;
        }
        /// <summary>
        /// 请求放入队列 生产环境建议更换Redis队列,Redis队列不支持持久化,缓存可以使用
        /// </summary>
        /// <param name="data"></param>
        private void Addredis(Record lr)
        {
            var no = 0;
            var num = Cache.Get("num");
            if (num == null)
            {
                Cache.Insert("num", 1);
                no = 1;
            }
            else
            {
                no = Convert.ToInt32(num) + 1;
                Cache.Insert("num", no);
            }
            //把记录插入缓存队列【Record】
            //时间秒 3600秒
            //var list = GetPeerList.Get();
            Cache.Insert<Record>("_" + no, lr, 3600); //id_100 {record}
            //发布
            Cache.Sub("peer", "_" + no);
        }

    }
}